package com.example.behaviour.proxy.dynamic.cglib;

import net.sf.cglib.proxy.Enhancer;
import net.sf.cglib.proxy.MethodInterceptor;
import net.sf.cglib.proxy.MethodProxy;

import java.lang.reflect.Method;

/**
 * @Author douhy
 * @description 代理工厂类(cglib)
 * @date 22/01/20
 */
public class ProxyFactory implements MethodInterceptor {

    private SpicyHotPot spicyHotPot = new SpicyHotPot();

    @Override
    public Object intercept(Object obj, Method method, Object[] args, MethodProxy proxy) throws Throwable {
        System.out.println("cglib代理，方法执行前执行");
        Object invoke = method.invoke(spicyHotPot, args);
        System.out.println("原方法执行结果：" + invoke);
        return "cglib代理返回 0";
    }

    public SpicyHotPot getProxyObject(){
        // 拿到工厂类
        Enhancer enhancer = new Enhancer();

        // 设置父字节码
        enhancer.setSuperclass(SpicyHotPot.class);

        // 回调地点
        enhancer.setCallback(this);

        // 创建代理对象
        SpicyHotPot spicyHotPot = (SpicyHotPot)enhancer.create();
        return spicyHotPot;
    }
}
